<template>
  <BoTable
    :columns="columns"
    :request="getPushList"
    ref="tableRef"
    row-key="id"
    :row-selection="rowSelection"
    :show-index="true"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增静默策略 </Button>
        <Button :disabled="!selectKeys?.length" @click="onDelete()"
          >删除</Button
        >
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items"> </FormModal>
</template>
<route lang="json">
{
  "name": "push",
  "meta": {
    "title": "告警推送"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import {
  Button,
  DatePicker,
  Input,
  Modal,
  Space,
  message,
} from 'ant-design-vue';
import { FormItem } from 'ant-design-vue/es/form';
import { addPush, deletePush, getPushList, updatePush } from './api';

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

const dictArr = ['notice_type'];
const { noticeTypeEnum, noticeTypeOptions } = useDicts(dictArr);

const noticeObjEnum = ref({});
const init = async () => {
  noticeObjEnum.value = listToEnum([
    {
      label: '运维组',
      value: '0',
    },
    {
      label: '值班组',
      value: '1',
    },
    {
      label: '其他组',
      value: '2',
    },
  ]);
};
init();

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '策略名称',
    dataIndex: 'name',
  },
  {
    title: '通知对象',
    dataIndex: 'noticeObj',
    hideInSearch: true,
    customRender({ record }) {
      const showObj =
        record.noticeObj && record.noticeObj.includes(',')
          ? record.noticeObj
              .split(',')
              .map((item) => noticeObjEnum.value[item]?.text)
              .join('、')
          : '';

      return <div>{showObj}</div>;
    },
  },
  {
    title: '通知方式',
    dataIndex: 'noticeType',
    hideInSearch: true,
    customRender({ record }) {
      const noticeTypeObj = record.noticeType.includes(',')
        ? record.noticeType
            .split(',')
            .map((item) => noticeTypeEnum.value[item]?.text)
            .join('、')
        : '';

      return <div>{noticeTypeObj}</div>;
    },
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    hideInSearch: true,
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions() {
      return [
        {
          text: '详情',
          onClick(record) {
            onView(record);
          },
        },
      ];
    },
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '策略名称',
    dataIndex: 'name',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入策略名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入策略名称',
    },
  },
  {
    title: '通知对象',
    dataIndex: 'noticeObj',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入标签类型',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入标签类型',
      mode: 'multiple',
      options: [
        {
          label: '运维组',
          value: '0',
        },
        {
          label: '值班组',
          value: '1',
        },
        {
          label: '其他组',
          value: '2',
        },
      ],
    },
  },
  {
    title: '通知方式',
    dataIndex: 'noticeType',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择通知方式',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择通知方式',
      options: noticeTypeOptions.value,
      mode: 'multiple',
    },
  },
  {
    title: '通知模板',
    dataIndex: 'template',
    valueType: 'input',
    fieldProps: {
      placeholder: '请输入模板内容',
    },
    render(record: any) {
      return (
        <div>
          <FormItem
            label='告警等级：'
            name='alarmLevel'
            rules={[{ required: true, message: '请输入告警等级' }]}
          >
            【
            <Input
              v-model:value={record.alarmLevel}
              style='width: 60px;padding: 0 4px'
              placeholder='普通'
            />
            】
          </FormItem>
          <FormItem
            label='告警时间：'
            name='alarmTime'
            rules={[{ required: true, message: '请选择告警时间' }]}
          >
            【
            <DatePicker
              v-model:value={record.alarmTime}
              format='YYYY-DD-MM HH:mm:ss'
              valueFormat='YYYY-DD-MM HH:mm:ss'
            />
            】
          </FormItem>

          <div class='leading-8'>
            告警描述：【
            <FormItem
              name='memoryRate'
              class='inline-block'
              rules={[{ required: true, message: '请输入告警描述' }]}
            >
              <Input
                v-model:value={record.memoryRate}
                style='width: 60px;padding: 0 4px'
                placeholder='普通'
              />
            </FormItem>
            】实际【
            <FormItem
              name='actualRate'
              class='inline-block'
              rules={[{ required: true, message: '请输入实际阈值' }]}
            >
              <Input
                v-model:value={record.actualRate}
                style='width: 60px;padding: 0 4px'
                placeholder='88%'
              />
            </FormItem>
            】大于阈值【
            <FormItem
              name='maxRate'
              class='inline-block'
              rules={[{ required: true, message: '请输入最高阈值' }]}
            >
              <Input
                v-model:value={record.maxRate}
                style='width: 60px;padding: 0 4px'
                placeholder='88%'
              />
            </FormItem>
            】且在【
            <FormItem
              name='dateRange'
              class='inline-block'
              rules={[{ required: true, message: '请输入时间' }]}
            >
              <Input
                v-model:value={record.dateRange}
                style='width: 60px;padding: 0 4px'
                placeholder='10小时'
              />
            </FormItem>
            】内重复触发【
            <FormItem
              name='repeatTimes'
              class='inline-block'
              rules={[{ required: true, message: '请输入允许的重复次数' }]}
            >
              <Input
                v-model:value={record.repeatTimes}
                style='width: 30px;padding: 0 4px'
                placeholder='4'
              />
            </FormItem>
            】次超过阈值【
            <FormItem
              name='repeatTimes'
              class='inline-block'
              rules={[{ required: true, message: '请输入允许的超过阈值次数' }]}
            >
              <Input
                v-model:value={record.throld}
                style='width: 30px;padding: 0 4px'
                placeholder='4'
              />
            </FormItem>
            】次
          </div>
        </div>
      );
    },
  },
  {
    title: '是否启用',
    dataIndex: 'status',
    valueType: 'switch',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择是否启用',
          trigger: 'blur',
        },
      ],
    },
  },
]);

const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
});

const onView = (record) => {
  const noticeObj = record.noticeObj?.split(',');
  const noticeType = record.noticeType?.split(',');
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    request: async (params: any) => {
      console.log(params, 'params');
      await updatePush(params);
      tableRef.value.refresh();
    },
    defaultValue: {
      ...record,
      noticeObj,
      noticeType,
    },
  });
};

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {
      status: '0',
      alarmLevel: '',
      alarmTime: '',
      memoryRate: '',
      actualRate: '',
      dateRange: '',
      repeatTimes: '',
      throld: '',
    },
    request: async (params: any) => {
      await addPush(params);
      tableRef.value.refresh();
    },
  });
};

const onDelete = async (record = null) => {
  const ids = record ? record.id : selectKeys.value.join();
  console.log(ids, 'ids');
  if (!ids) return message.info('请选择要删除的数据');
  Modal.confirm({
    title: '系统提示',
    content: `确定删除当前选中项数据吗?`,
    onOk: async () => {
      await deletePush(ids);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};
</script>

<style lang="scss" scoped></style>
